package com.gxd.dao.impl;

import com.gxd.dao.CartDao;
import com.gxd.domain.Cart;
import com.gxd.util.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.taglibs.standard.tag.common.fmt.ParamSupport;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class CartDaoImpl implements CartDao {
    QueryRunner queryRunner = new QueryRunner(DBUtils.getDataSource());
    @Override
    public Cart findUidAndPid(int uid, int goodsId) {
        String sql=" select id,pid,num,money from tb_cart where id=? and pid=? ";
        try {
            return queryRunner.query(sql,new BeanHandler<>(Cart.class),uid,goodsId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void insert(Cart cart) {

        String sql=" insert into tb_cart values(?,?,?,?) ";
        Object[] params={cart.getId(),cart.getPid(),cart.getNum(),cart.getMoney()};
        try {
            queryRunner.update(sql, params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void update(Cart cart) {
        String sql=" update tb_cart set num=?,money=? where id=? and pid=? ";
        Object[] params={cart.getNum(),cart.getMoney(),cart.getId(),cart.getPid()};
        try {
            queryRunner.update(sql, params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Cart> findUid(int id) {
        String sql=" select id,pid,num,money from tb_cart where id=?  ";
        try {
            return queryRunner.query(sql,new BeanListHandler<>(Cart.class),id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void delete(int id, int pid) {
        String sql=" delete  from tb_cart where id=? and pid=? ";
        try {
             queryRunner.update(sql,id,pid);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void clearCart(int id) {
        QueryRunner queryRunner =new QueryRunner();
        Connection connection = DBUtils.getConnection();
        String sql=" delete  from tb_cart where id=? ";
        try {
            queryRunner.update(connection,sql,id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
